package com.wit.witmg.util;

import net.coobird.thumbnailator.Thumbnails;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class FileUtil {
    public static void saveFile(MultipartFile file, String imgPath){
        try {

            File newFile = new File(imgPath);
//            if (!newFile.exists()) {
//                newFile.mkdirs();
//            }
            file.transferTo(newFile);// 将内存中的数据写入磁盘
//            if(ImageIO.read(newFile)!=null){//图片文件
//                String prefix= imgPath.substring(imgPath.lastIndexOf("."),imgPath.length());
//                int resIndex=imgPath.lastIndexOf("/");
//                String path=imgPath.substring(0,resIndex+1);
//                String name="thumb_"+ imgPath.substring(resIndex+1,imgPath.length());
//                String imgThumbPath=path+name;
//                //生成缩略图
//                Thumbnails.of(newFile).scale(0.2d).outputQuality(0.3).outputFormat(prefix).toFile(imgThumbPath);
//            }
        }catch (Exception e){}
    }

    public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream out = new FileOutputStream(filePath+fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    //带缩略图的 图片保存
    public static void saveImg(MultipartFile file,String imgPath,String imgThumbPath,String prefix){
        try {
            File newFile = new File(imgPath);
            file.transferTo(newFile);// 将内存中的数据写入磁盘
            //生成缩略图
            if(newFile.length()<=50*1024){
                Thumbnails.of(newFile).scale(1f).toFile(imgThumbPath);
            }else {
                Thumbnails.of(newFile).outputQuality(0.3).outputFormat(prefix).toFile(imgThumbPath);
            }
        }catch (Exception e){}
    }

    public static void mkdir(String filePath){
        File targetFile = new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
    }

    public static void del(File fileTemp) {
        if(fileTemp!=null) {
            fileTemp.delete();
        }
    }

    //java 通过url下载图片保存到本地
    public static void download(String urlString, String savePath) {
        try {
            // 构造URL
            URL url = new URL(urlString);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File file = new File(savePath); //下载路径及下载图片名称
            if (file.exists()) file.delete();
            FileOutputStream os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
        }catch (Exception e){}
    }

    /**
     * @param fileUrl 资源地址
     * @Description: 网络资源转file, 用完以后必须删除该临时文件
     * @return: 返回值
     */
    public static File urlToFile(String fileUrl, String savePath) {
        FileOutputStream downloadFile = null;
        InputStream openStream = null;
        File savedFile = null;
        try {
            savedFile = new File(savePath);
            if(!savedFile.exists()){
                savedFile.mkdirs();
            }
            URL url = new URL(fileUrl);
            java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
            connection.setRequestProperty("User-agent","Mozilla/4.0");
            openStream = connection.getInputStream();
            int index;
            byte[] bytes = new byte[1024];
            downloadFile = new FileOutputStream(savedFile);
            while ((index = openStream.read(bytes)) != -1) {
                downloadFile.write(bytes, 0, index);
                downloadFile.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (openStream != null) {
                    openStream.close();
                }
                if (downloadFile != null) {
                    downloadFile.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return savedFile;
    }

    public static File convert(MultipartFile file)
    {
        File convFile = new File(file.getOriginalFilename());
        try {
            convFile.createNewFile();
            FileOutputStream fos = new FileOutputStream(convFile);
            fos.write(file.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return convFile;
    }

    //图片 byte 裁剪
    public static byte[] cropImage(byte[] originalImageBytes, int x, int y, int width, int height) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(originalImageBytes));
        // 创建裁剪区域
        Rectangle cropRect = new Rectangle(x, y, width, height);
        // 裁剪图片
        BufferedImage croppedImage = originalImage.getSubimage(cropRect.x, cropRect.y, cropRect.width, cropRect.height);
        // 将裁剪后的图片写入字节数组输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(croppedImage, "jpg", outputStream);

        // 将字节数组输出流转换为字节数组
        return outputStream.toByteArray();
    }
}
